using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace PocoReport
{
    public class Scope
    {
        private readonly Dictionary<string, object> _dataSource;

        public Scope(Dictionary<string, object> dataSource)
        {
            _dataSource = dataSource;
        }

        public Scope(Scope scope)
        {
            _dataSource = new Dictionary<string, object>(scope._dataSource);
        }

        public string FieldEvaluator(Match match)
        {
            string field = match.Groups[1].Value;
            string format = match.Groups[3].Value;
            object value = GetValue(field);
            return string.IsNullOrEmpty(format) ? 
                string.Format("{0}", value) : 
                string.Format("{0:" + format + "}", value);
        }

        public object GetValue(string field)
        {
            string[] fieldParts = field.Split('.');
            object value = _dataSource[fieldParts[0]];
            for (int i = 1; i < fieldParts.Length; i++)
            {
                string fieldPart = fieldParts[i];
                value = value.GetType().GetProperty(fieldPart).GetValue(value, null);
            }
            return value;
        }

        public void Set(string name, object value)
        {
            _dataSource[name] = value;
        }
    }
}